import {
  Injectable,
  CanActivate,
  ExecutionContext,
  BadRequestException,
  Logger,
} from '@nestjs/common';

import { EMAIL_REGEX_RULE } from '@app/common';

@Injectable()
export class RegexEmailGuard implements CanActivate {
  private readonly logger = new Logger(RegexEmailGuard.name);

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const email = request.user?.email;
    this.logger.debug('request.user?.email => ' + email);
    if (!EMAIL_REGEX_RULE.test(email)) {
      throw new BadRequestException(
        '当前操作需要邮件验证，请您先绑定邮件信息，方可继续操作。',
      );
    }
    return true;
  }
}
